package com.licheedev.demo.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.HashMap;
import java.util.Map;

public class NioServer {
    //  private static final Logger logger = LoggerFactory.getLogger(NioServer.class);
    //连接map
    public  static Map<String, ChannelHandlerContext> map = new HashMap<String, ChannelHandlerContext>();
    //默认端口
    private Integer defaultPort=8000;
    public void bind(Integer port) throws Exception {
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.SO_KEEPALIVE, true) // 2小时无数据激活心跳机制
                    .childHandler(new ServerChannelInitializer());
            // 服务器异步创建绑定
            if(null==port){
                port=this.defaultPort;
            }
            ChannelFuture f = b.bind(port).sync();
            //   logger.info("服务启动："+ DateUtils.dateToString(new Date()));
            // 关闭服务器通道
            f.channel().closeFuture().sync();
        } finally {
            //  logger.info("服务停止："+ DateUtils.dateToString(new Date()));
            // 释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
